/* 
 * This file implements the route functions for url like '/xxx'
 *  both for gets and posts routes.
 *  specific: post routs begin with _
 *  example: _post_xxx
 */


/* 
 * module dependences
 */

//load the libs
var nodemailer = require("nodemailer");



//load the private libs
var settings  = require("../settings.js");
var cookies   = require("./cookies.js");
var user_stats_helper = require("./user_stats_helper.js");
var utils     = require("../utils.js");
var DBClasses = require("../modules/DBClasses.js");
var DB        = require("../modules/mdb.js").DB;
var Query     = require("../modules/Query.js").Query;


//------------------------------------

//extract the necessary information from the modules loaded above

var cookieName = cookies.cookieName;
var User       = DBClasses.User;

//
//export the handlers
//

exports.homepage_handler = homepage_handler;


exports.reg_handler = reg_handler;
exports._reg_handler = _reg_handler;


exports._checkNotLogin = _checkNotLogin;
exports._checkLogin    = _checkLogin;

exports.login_handler = login_handler;
exports._login_handler = _login_handler;

exports.logout_handler = logout_handler;



//-------------------


function addCookieUser(res,id){
    res.cookie(cookieName.userid, id, { path: '/',maxAge:
						utils.generate_time({days:30})});
    
}



function homepage_handler(req,res){
    
    
    //res.clearCookie("name");
    //secure option for the cookie seems to only work for https
   // res.cookie('name', 'test');//,{  domain:settings.domain,path:"/" });
    res.render("index",{title:"home"
		       });
}

function reg_handler(req,res){
    //must be called after the checkNotLogin check.
    res.render("reg",{title:"reg"});
}

function _reg_handler(req,res){

    var body = req.body;
    console.log(body);
    if(body.pw != body.ensure_pw){
	res.locals.error = "两次输入密码不一致";
	return res.redirect("/reg");
    }
    //handler the 3 infos that is not required to given.
    //to avoid the null information
    body.age = body.age || "-1";
    body.age = parseInt(body.age);    
    
    body.job = body.job || "not given";
    body.address = body.address || "not given";

    //connect the db
    var db = new DB();

    var query = new Query();
    query.start("email").eq(body.email).done();

    db.findOne(settings.userCollection,	       
	       query,
	       function(err){  
		   console.log(err);
		   res.locals.error = err;
		   return res.redirect("/reg");
	       },
	       function(doc){
		   
		   if(doc){
		       console.log("reg user already exesisted");
		       res.locals.error = "该邮箱已注册";
		       
		       return res.redirect("/reg");
		       
		   }
		   //we will change the password later
		   var user = new User(body.name,body.age,body.email,body.phone,"*",utils.generate_salt(),body.address,	body.job,0);
		   console.log(user);
		   //change the password 
		   user.password = utils.password_salt(body.pw,user.salt);

		   //save it back to the db
		   db.save(settings.userCollection,user,
			   function(err){
			       console.log(err);
			       res.locals.error = err;
			       return res.redirect("/reg");
			   },
			   function(){
			       addCookieUser(res,body.email);
			       //
			       //now we send the certificate mail to the user
			       
			       return res.redirect("/");
			   });
			   
	       });
	       

}

function login_handler(req,res){
    
    res.render("login",{title:"login"});
    
}

function _login_handler(req,res){
    

    var body = req.body;

    //connect the db
    var db = new DB();
    var query = new Query();    
    query.start("email").eq(body.user_name).done();
    
    //find the specified user
    db.findOne(settings.userCollection,query,
	       function(err){
		   res.locals.error = err;
		   return res.redirect("/login");
		   
	       },
	       function(doc){
		   if(!doc){
		       console.log("user not exesists");
		       res.locals.error = "用户不存在";
		       return res.redirect("/login");
		       
		   }
		   //check password
		   if(doc.password != utils.password_salt(body.user_password,
							  doc.salt)){
		       res.locals.error = "密码不正确";
		       return res.redirect("/login");
		   }
		   //beacuse salt and password may not be revaled to the user
		   res.locals.user = new User(doc.real_name,doc.age,
					      doc.email,doc.mobile,"*","*",
					      doc.address,doc.profession,
					      doc.permissions);
		   //may pass new params
		   //
		   addCookieUser(res,body.user_name);
		   res.redirect("/");
		   
	       });
	      
	       
    
}


function _checkNotLogin(req,res,next){
    
    //This is a wrapper function for all path that needs to assure that the user not logined.
    //for example,the login page will not present to the logged user.

    if(req.cookies[cookieName.userid]){
	//user stats get.0	
	res.redirect("/");
    }
    res.locals.user = null;
    next();
}

function _checkLogin(req,res,next){
    //This is a wrapper function for all path that needs to assure that the user has logined.
    //for example,the logout request must assure the user has logged in.
    if(!req.cookies[cookieName.userid]){
	res.locals.error = "未登录";
	console.log(res.locals.error);
	res.redirect("/login");
	
    }
    next();
}

function logout_handler(req,res){
    
    //simply clear the cookies.
    res.clearCookie(cookieName.userid);
    res.locals.user = null;
    res.redirect("/");

}
